package com.viu.technology.chat.listener;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.viu.technology.dto.ChatMessage;
import com.viu.technology.service.message.MessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.*;

@Component
@Configuration
public class ChatDurableListener {

    private static Logger log = LoggerFactory.getLogger(ChatDurableListener.class);

    @Autowired
    private ConnectionFactory connectionFactory;

    @Autowired
    private ChatDurableHandler chatDurableHandler;


    @Bean
    public SimpleMessageListenerContainer messageContainer(@Autowired Executor rabbitListenerExecutor) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.setQueues(new Queue("queue.chat.durable"));
        container.setExposeListenerChannel(true);
        container.setMaxConcurrentConsumers(500);
        container.setConcurrentConsumers(200);
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);//消息确认后才能删除
        container.setPrefetchCount(5);//每次处理5条消息
        container.setTaskExecutor(rabbitListenerExecutor);

        container.setMessageListener(chatDurableHandler);
        return container;
    }




    /*//注解方式监听消息队列
    @RabbitListener(queues = {"queue.chat.durable"})
    public String process(Message message, Channel channel) throws IOException {
        log.info("Receiver1  : " + new String(message.getBody()));
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false );
        return "";
    }*/
}
